package home.utils;

import home.anno.AutoWired;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class SimpleContainer {
    private static HashMap<Class<?>, Object> map = new HashMap<Class<?>, Object>();

    //根据id获取对象
    public static <T> T getBean(Class<T> beanClass) {
        return (T)map.get(beanClass);
    }

    //根据id获取对象
    public static void addBean(Class<?> beanClass) {
        try {
            Constructor<?> constructor = beanClass.getConstructor();
            Object o = constructor.newInstance();
            map.put(beanClass,o);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //根据id获取对象
    public static void injectDepend(Object bean) {
        Class<?> aClass = bean.getClass();

        Field[] fields = aClass.getFields();

        for (Field field : fields) {
            if(field.isAnnotationPresent(AutoWired.class)){
                Class<?> type = field.getType();

                Object bean1 = getBean(type);

                try {
                    field.set(bean,bean1);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }


}
